<?php

namespace App\Trip\Weather\Amap;

use App\Trip\Geo\Amap\Amap;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class Weather extends Amap
{

    /**
     * 查询天气
     *
     * @param string   $city_id
     * @param int|null $type
     *
     * @return mixed|array
     * @throws GuzzleException
     * @throws Exception
     */
    public function weatherInfo(string $city_id, ?int $type = 1): mixed
    {
        // 实况天气每小时更新多次，预报天气每天更新3次，分别在8、11、18点左右更新
        $cache_key = "Amap:weather:{$city_id}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }

        $res = app('weather')->getLiveWeather($city_id);
        if (!isset($res['lives'])) {
            throw new Exception("天气查询失败");
        }
        $data = collect($res['lives'])->map(fn($v) => [
            'province'      => $v['province'],
            'city'          => $v['city'],
            'adcode'        => $v['adcode'],
            'weather'       => $v['weather'],
            'temperature'   => $v['temperature'],
            'winddirection' => $v['winddirection'],
            'windpower'     => $v['windpower'],
            'humidity'      => $v['humidity'],
            'reporttime'    => $v['reporttime'],
        ])->toArray();
        Cache::put($cache_key, $data, config('trip.ttl.hour'));
        return $data;

    }
}